﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Portal.Api;
using Portal.FileSystemData;


namespace Portal.Modules.ImageBrowser
{
  /// <summary>
  /// Summary description for DataAccessor
  /// </summary>
  public class DataAccessor
  {
    ModuleDocument _moduleDoc;
    DirectoryWrapper _rootDirectory;
    ImageBrowserConfig _config;

    public DataAccessor(Portal.Api.ModuleDocument moduleDoc)
    {
      _moduleDoc = moduleDoc; 
    }


    public ModuleDocument ModuleDocument
    {
      get { return _moduleDoc; }
    }

    /// <summary>
    /// The module Configuration.
    /// </summary>
    public ImageBrowserConfig Config
    {
      get
      {
        if(_config == null)
        {
          _config = (ImageBrowserConfig)_moduleDoc.ReadConfig(typeof(ImageBrowserConfig));
          if (_config == null)
            _config = new ImageBrowserConfig();
        }
        return _config;
      }
    }


    /// <summary>
    /// The DirectoryWrapper for the root directory.
    /// </summary>
    public DirectoryWrapper RootDirectory
    {
      get 
      {
        // Load the data only the first time.
        if(_rootDirectory == null)
        {
          // Try to load the data from the cache.
          object cacheContent = HttpContext.Current.Cache[CacheKey];
          if(cacheContent == null)
          {
            if (Config != null)
            {
              // Do some data updates, if necessary.
              ImageBrowserUpdater updater = new ImageBrowserUpdater();
              updater.Update(Config);

              // Add the data to the cache.
              _rootDirectory = new DirectoryWrapper(Config.PicturePhysicalPath, null);
              HttpContext.Current.Cache.Insert(CacheKey, _rootDirectory);
            }
          }
          else
            _rootDirectory = cacheContent as DirectoryWrapper;
        }
        return _rootDirectory;
      }
    }

    private DirectoryWrapper CreateRootDirectoryWrapper()
    {
      DirectoryWrapper rootDirectory = null;
      if (System.IO.Directory.Exists(Config.PicturePhysicalPath))
        rootDirectory = new DirectoryWrapper(Config.PicturePhysicalPath, null);
      return rootDirectory;
    }

    /// <summary>
    /// Reloads the root directory after a configuration change.
    /// </summary>
    public void ReloadRootDirectory()
    {
      HttpContext.Current.Cache.Remove(CacheKey);
      _rootDirectory = null;
    }


    private string CacheKey
    {
      get { return _moduleDoc.ModuleRef + "RootDirectory"; }
    }
    
  }
}